#!/usr/bin/perl
#
# Copyright Jean-Samuel Reynaud <js.reynaud@free.fr>
# Licenced under GPL v2
#
# We use this script to produce graph with munin for dns requests
# This script must have his name start with bind_
# bind_ : Global bind statistic
# bind_test.com : Bind statistic for test.com zone
#
# Thanks for Benjamin Pineau for perl cleaning and correction in non root
# running
#
# Magic markers
#%# family=auto
#%# capabilities=autoconf

use strict;
use warnings;

# change those to reflect your bind configuration
# stat file
#my $stat_file = "/var/cache/bind/named.stats";
my $stat_file = "/var/run/bind/run/named.stats";
# rndc path
my $rndc = "/usr/sbin/rndc";



my $lst = { "success" => 1,
            "referral" => 1,
            "nxrrset" => 1,
            "nxdomain" => 1,
            "recursion" => 1,
            "failure" => 1};

my $domain = $0;
$domain =~ s/^.*bind_?([\w\d\._\-]*)$/$1/;


# Parse the statistic file
sub parseFile {
    my $dom = shift @_;
    open(IN,"<$stat_file") or die "Can't open $stat_file : $!";

    while (<IN>) {
        chomp;
        my ($type,$count,$zone) = split(/ /,$_);
        $zone = defined($zone) ? $zone : "";
        if ($zone eq $dom) {
            if (defined $lst->{$type}) {
                # only keep the latest occurence for each value
                $lst->{$type} = $count;
            }

        }
    }

    close(IN);
    printf "%s.value %u\n", $_, $lst->{$_} foreach (keys %$lst);
}



# Config mode
if ( defined($ARGV[0]) && $ARGV[0] eq "config" ) {
    printf "graph_title Dns requests %s\n",($domain eq "" ? " all domains":$domain);
    printf "graph_vlabel requests/s\n";
    printf "graph_category network\n";
    printf "graph_info This graph display dns requests for   %s\n",($domain eq "" ? " all domains":$domain);
    printf "success.label Success\n";
    printf "success.type COUNTER\n";

    printf "referral.label Referral\n";
    printf "referral.type COUNTER\n";

    printf "nxrrset.label Nx RR set\n";
    printf "nxrrset.type COUNTER\n";

    printf "nxdomain.label NX domain\n";
    printf "nxdomain.type COUNTER\n";

    printf "recursion.label Recursion\n";
    printf "recursion.type COUNTER\n";

    printf "failure.label Failure\n";
    printf "failure.type COUNTER\n";

    exit 0;
}

if ( defined($ARGV[0]) && $ARGV[0] eq "autoconf" ) {
    if (! -f $stat_file) {
        printf "Unable to file bind stat file on %s",$stat_file;
        exit 1;
    }
    if (! -f $rndc) {
        printf "Unable to file rndc tool (configured : %s)",$rndc;
        exit 1;
    }
    exit 0;
}

# Remove old stat file
unlink ($stat_file);
# Ask to bind to build new one
`$rndc stats`;
# Parse the stat file and return result
parseFile($domain);
